package com.csmk.springboot_simple.base;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.lang.reflect.Field;
import java.util.List;

public class BaseServiceImpl<M extends BMapper<T>,T> extends ServiceImpl<M,T> implements BaseService<T>{

    @Override
    public int saveOrUpdateAll(List<T> list) {
        if (list == null || list.size() == 0) {
            return 0;
        }

        Class<T> tClass = getEntityClass();
        // 反射获取被TableId注解的字段
        Field tableIdField = null;
        for (Field field : tClass.getDeclaredFields()) {
            if(field.isAnnotationPresent(TableId.class)){
                TableId tableIdAnnotation = field.getAnnotation(TableId.class);
                if (tableIdAnnotation.type() == IdType.AUTO){
                    // 不是auto就让它为null了 不生成id了
                    tableIdField = field;
                }
                break;
            }
        }
        // 有被标记的id字段
        if(tableIdField != null){
            tableIdField.setAccessible(true);
            try{
                // 为被标记的字段生成 id
                for (T t : list) {
                    if(tableIdField.get(t) == null){
                        Long id = genId();
                        if(tableIdField.getType().equals(Long.class)){
                            tableIdField.set(t, id);
                        }else if(tableIdField.getType().equals(String.class)){
                            tableIdField.set(t, id.toString());
                        }
                    }
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }


        return baseMapper.saveOrUpdateAll(list);
    }


}
